﻿@using hc.epm.Common;
@using hc.Plat.Common.Extend;
@using hc.epm.ViewModel;
@model ChangeView
@using hc.epm.Common;
@using hc.Plat.Common.Extend;
@{
    ViewBag.Title = "修改变更";
}
<body>
    <div class="contentData">
        <form id="mainForm">
            <div class="tab">
                <div class="long-text">
                    <label for="PrejectName"><span class="star">*</span>&nbsp;项目名称&nbsp;:</label>
                    <input type="text" id="ProjectName" name="ProjectName" value="@Model.ProjectName" autocomplete="off" />
                    <i class="pic iconfont" width="20" height="30" style="cursor:pointer; left:596px;">&#xe76a;</i>
                    <input type="hidden" name="ProjectId" id="ProjectId" value="@Model.ProjectId" />
                </div>
                <input type="hidden" name="id" value="@Model.Id">
                <div class="long-text">
                    <label for="ChangeNo"><span class="star">*</span>&nbsp;变更名称&nbsp;:</label>
                    <input type="text" id="ChangeName" name="ChangeName" value="@Model.ChangeName" autocomplete="off" />
                </div>
                <div class="intro">
                    <div><label for="ChangeContent"><span class="star"></span>&nbsp;变更内容&nbsp;:</label></div>
                    <div>
                        <textarea class="sub-description" id="ChangeContent" name="ChangeContent">@Model.ChangeContent</textarea>
                    </div>
                </div>
                <div class="intro">
                    <div><label for="ChangeReason"><span class="star"></span>&nbsp;变更原因&nbsp;:</label></div>
                    <div>
                        <textarea class="sub-description" id="ChangeReason" name="ChangeReason">@Model.ChangeReason</textarea>
                    </div>
                </div>
                <div class="long-text">
                    <label for="ChangeNo"><span class="star"></span>&nbsp;变更号&nbsp;:</label>
                    <input type="text" id="ChangeNo" name="ChangeNo" value="@Model.ChangeNo" autocomplete="off" />
                </div>
                <div class="long-text">
                    <label for="TotalAmount"><span class="star">*</span>&nbsp;项目总金额&nbsp;:</label>
                    <input type="text" id="TotalAmount" name="TotalAmount" value="@Model.TotalAmount.ToString("#0")" readonly style="background: #ebebe5;" />&nbsp;&nbsp;&nbsp;万元
                </div>
                <div class="long-text">
                    <label for="AddAmount"><span class="star"></span>&nbsp;调增额&nbsp;:</label>
                    <input type="text" id="AddAmount" name="AddAmount" value="@Model.AddAmount.ToString("#0")" />&nbsp;&nbsp;&nbsp;万元
                </div>
                <div class="long-text">
                    <label for="ReduceAmount"><span class="star"></span>&nbsp;调减额&nbsp;:</label>
                    <input type="text" id="ReduceAmount" name="ReduceAmount" value="@Model.ReduceAmount.ToString("#0")" />&nbsp;&nbsp;&nbsp;万元
                </div>
                <div class="long-text">
                    <label for="ChangeAmount"><span class="star">*</span>&nbsp;变更金额&nbsp;:</label>
                    <input type="text" id="ChangeAmount" name="ChangeAmount" value="@Model.ChangeAmount.ToString("#0")" readonly style="background: #ebebe5;" />&nbsp;&nbsp;&nbsp;万元
                </div>
                @*<div class="long-text">
                        <label><span class="star">*</span>&nbsp;变更涉及单位&nbsp;:</label>
                        <input type="text" name="CompanyNames" id="CompanyNames" value="@Model.CompanyNames" autocomplete="off" />
                        <i class="pic iconfont ff" width="20" height="30" style="cursor:pointer; left:596px;">&#xe76a;</i>
                        <input type="hidden" name="CompanyIds" id="CompanyIds" value="@Model.CompanyIds" autocomplete="off" />
                    </div>
                    <div class="long-text">
                        <label for="SubmitUserName"><span class="star">*</span>&nbsp;变更发起人&nbsp;:</label>
                        <input type="text" id="SubmitUserName" name="SubmitUserName" value="@Model.SubmitUserName" autocomplete="off" readonly style="background-color:#EBEBE4" />
                        <i class="pic iconfont ee" width="20" height="30" style="cursor:pointer; left:596px;">&#xe76a;</i>
                        <input type="hidden" id="SubmitUserId" name="SubmitUserId" value="@Model.SubmitUserId" autocomplete="off" />
                    </div>*@

                <div class="short-text">
                    <label><span class="star">*</span>&nbsp;开始时间&nbsp;:</label>
                    <input type="text" id="ChangeStartTime" name="ChangeStartTime" onClick="WdatePicker({ el: 'ChangeStartTime' })" value="@(Model.ChangeStartTime == null ? "" : Convert.ToDateTime(Model.ChangeStartTime).ToString("yyyy-MM-dd"))" readonly="readonly" autocomplete="off">
                    <i onClick="WdatePicker({ el: 'ChangeStartTime' })" class="pic iconfont" width="20" height="30" style="cursor:pointer">&#xe7e2;</i>
                </div>
                <div class="short-text">
                    <label><span class="star">*</span>&nbsp;截止时间&nbsp;:</label>
                    <input type="text" id="ChangeEndTime" name="ChangeEndTime" onClick="WdatePicker({ el: 'ChangeEndTime' })" value="@(Model.ChangeEndTime == null ? "" : Convert.ToDateTime(Model.ChangeEndTime).ToString("yyyy-MM-dd"))" readonly="readonly" autocomplete="off">
                    <i onClick="WdatePicker({ el: 'ChangeEndTime' })" class="pic iconfont" width="20" height="30" style="cursor:pointer">&#xe7e2;</i>
                </div>
                <div class="upload" style="margin-bottom:0px;">
                    <div><label>&nbsp;附件上传&nbsp;:</label></div>
                    <div class="btn-upload">
                        <button id="btnUploadFile" style="position: relative; z-index: 1;">上传附件</button>
                        <span style="vertical-align:bottom; margin-left:15px; color:#B7B7B7;">支持doc、xls、pdf、图片、视频、压缩文件格式</span>
                    </div>
                </div>
                <div style="width:100%;" id="fileListFile">
                    <ul class="fileShow"></ul>
                    <input type="hidden" name="fileDataJsonFile" id="fileDataJsonFile">
                </div>
                <div class="button-group btn-center">
                    @if ((((ApprovalState)Model.State).GetText()) == "待审核")
                    {
                        <button type="button" class="saveBut" data-state="@(ApprovalState.WaitAppr.GetValue().ToString())">提交</button>
                        <button type="button" class="Audit checkright" data-module="Contract" data-right="Check">审核</button>
                        <button type="button" class="Reject checkright" data-module="Contract" data-right="UnCheck">驳回</button>
                        <a href="javascript:;" class="exchange">沟通</a>
                    }
                    else if ((((ApprovalState)Model.State).GetText()) == "审核不通过")
                    {
                        <button type="button" class="saveBut" data-state="@(ApprovalState.WaitAppr.GetValue().ToString())">提交</button>
                        <button type="button" class="Discard checkright" data-module="Contract" data-right="Invalid">废弃</button>
                        <button type="button" class="exchange">沟通</button>

                    }
                    else {
                        <button type="button" class="saveBut" data-state="@(ApprovalState.WaitAppr.GetValue().ToString())">提交</button>
                        <button type="button" class="exchange">沟通</button>
                    }

                    <input type="hidden" name="State" id="State" />

                </div>
            </div>
        </form>
    </div>
    <script>
        $(function () {
            $("#mainForm").validate({
                errorClass: "validaterror",
                validClass: "validatevalid",
                errorElement: "span",
                errorPlacement: function (error, element) {
                    error.appendTo(element.parent());
                    if (element.parent(".long-text")) {
                        element.parent(".long-text").append(error)
                        return
                    }
                },
                success: function (label) {
                    label.addClass("validatevalid").html("&nbsp;");
                },
                rules: {
                    ProjectName: {
                        required: true
                    },
                    ChangeName: {
                        required: true
                    },
                    TotalAmount: {
                        required: true,
                        number: true
                    },
                    ChangeAmount: {
                        required: true,
                        number: true
                    },
                    AddAmount: {
                        number: true
                    },
                    ReduceAmount: {
                        number: true
                    },
                    ChangeStartTime: {
                        required: true,
                        date: true
                    },
                    ChangeEndTime: {
                        required: true,
                        date: true
                    }
                },
                messages: {
                    ProjectName: {
                        required: "项目名称不能为空"
                    },
                    ChangeName: {
                        required: "变更名称不能为空"
                    },
                    TotalAmount: {
                        required: "项目总金额不能为空"
                    },
                    //CompanyNames: {
                    //    required: "变更涉及单位不能为空"
                    //},
                    ChangeAmount: {
                        required: "变更金额不能为空"
                    },
                    ChangeStartTime: {
                        required: "开始时间不能为空"
                    },
                    ChangeEndTime: {
                        required: "截止时间不能为空"
                    },
                    AddAmount: {
                        number: "调增额必须为数字"
                    },
                    ReduceAmount: {
                        number: "调减额必须为数字"
                    },
                }
            });
            //判断开始时间和结束时间
            $("#ChangeStartTime,#ChangeEndTime").blur(function () {
                var strStartTime = $("#ChangeStartTime").val();
                var endTime = $("#ChangeEndTime").val();
                var startNum = parseInt(strStartTime.replace(/-/g, ''), 10);
                var endNum = parseInt(endTime.replace(/-/g, ''), 10);
                if (startNum > endNum) {
                    layer.alert("截止时间不能小于开始时间!", { icon: 2 });
                    $("#ChangeEndTime").val("");
                    $("#mainForm").valid()//重新验证inputName
                      .updateStatus('ChangeEndTime', 'NOT_VALIDATED', null)
                      .validateField('ChangeEndTime');
                    return false;
                }
            });

            $("#AddAmount,#ReduceAmount").blur(function () {
                var addAmount = $("#AddAmount").val();  //调增额
                var reduceAmount = $("#ReduceAmount").val(); //调减额

                if (addAmount == "" && reduceAmount == "") {
                    $("#ChangeAmount").val(0);
                } else if (addAmount == "" && reduceAmount != "") {
                    $("#ChangeAmount").val(parseInt(reduceAmount));
                } else if (addAmount != "" && reduceAmount == "") {
                    $("#ChangeAmount").val(parseInt(addAmount));
                }
                else {
                    $("#ChangeAmount").val(parseInt(addAmount) + parseInt(reduceAmount));
                }
            });

            //数据提交
            $(".saveBut").click(function () {
                if ($("#mainForm").valid()) {
                    var state = $(this).data("state");
                    $("#State").val(state);
                    var addAmount = $("#AddAmount").val();  //调增额
                    var reduceAmount = $("#ReduceAmount").val(); //调减额
                    if (addAmount == "" && reduceAmount == "") {
                        layer.alert("需要填写调增额和调减额中的任意一个", { icon: 7 });
                        return;
                    }
                    if (Number(parseInt(addAmount)) < 0) {
                        layer.alert("调增额应为正数", { icon: 7 });
                        return;
                    }
                    if (Number(parseInt(reduceAmount)) > 0) {
                        layer.alert("调减额应为负数", { icon: 7 });
                        return;
                    }
                    var search = $("form").serialize();
                    $.post("Edit", search, function (data) {
                        if (data.Flag) {
                            layer.msg("操作成功", { time: 1000, icon: 1 }, function () {
                                window.location.href = "/Change/Index";
                            });
                        } else {
                            layer.alert(data.Message, { icon: 2 });
                        }
                    });
                }
            });
        })

        layui.use(['layer', 'form', 'element', 'laypage'], function () {
            var layer = layui.layer, form = layui.form, element = layui.element, $ = layui.jquery, laypage = layui.laypage;
            //在建项目
            $("#ProjectName").click(function () {
                layer.open({
                    type: 2,
                    title: GetLayerTitle("选择在建项目"),
                    shadeClose: false, //点击遮罩关闭层
                    area: ['800px', '600px'],
                    content: '/Comm/SelectProject',
                    btn: ["确定", "取消"],
                    yes: function (index, layero) {
                        var iframeWin = window[layero.find('iframe')[0]['name']];
                        var obj = iframeWin.getSelectData();
                        if (obj && obj.flag && obj.data) {
                            $("#ProjectName").val(obj.data[0].Name);
                            $("#ProjectId").val(obj.data[0].Id);
                            parent.layer.close(index);//关闭窗口
                        } else if (!obj.flag) {
                            parent.layer.msg(obj.msg, { time: 1000, icon: 2 });
                            return false;
                        }
                    },
                    btn2: function (index, layero) {
                        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                        parent.layer.close(index);//关闭窗口
                    },
                    cancel: function (index, layero) {
                    },
                });
            });
            //变更涉及单位
            //$("#CompanyNames").click(function () {
            //    var projectName = $("#ProjectName").val();
            //    var projectId = $("#ProjectId").val();
            //    if (projectId == "" || projectName == "") {
            //        parent.layer.msg("请先选择项目", { time: 1000, icon: 2 });
            //        return false;
            //    }
            //    layer.open({
            //        type: 2,
            //        title: GetLayerTitle("选择单位"),
            //        shadeClose: false, //点击遮罩关闭层
            //        area: ['800px', '600px'],
            //        content: '/Comm/SelectCompany2?companyType=all&selectType=2&projectId=' + projectId,
            //        btn: ["确定", "取消"],
            //        yes: function (index, layero) {
            //            var iframeWin = window[layero.find('iframe')[0]['name']];
            //            var obj = frames['layui-layer-iframe' + index].getSelectData();
            //            if (obj.flag === false) {
            //                layer.alert(obj.msg, { icon: 2 });
            //            } else {
            //                for (var i = 0; i < obj.data.length; i++) {
            //                    var name = name + "," + obj.data[i].CompanyName;
            //                    var id = id + "," + obj.data[i].Id;
            //                    var names = name.slice(10);
            //                    var ids = id.slice(10);
            //                    $("#CompanyNames").val(names)
            //                    $("#CompanyIds").val(ids);
            //                }
            //                layer.close(index);
            //            }
            //        },
            //        btn2: function (index, layero) {
            //            var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
            //            parent.layer.close(index);//关闭窗口
            //        },
            //        cancel: function (index, layero) {
            //        },
            //    });
            //});
            //layer.open({
            //    type: 2,
            //    title: GetLayerTitle("选择单位"),
            //    shadeClose: false, //点击遮罩关闭层
            //    area: ['800px', '600px'],
            //    content: '/Comm/SelectCompany2?companyType=all&selectType=2&projectId=' + projectId,
            //    btn: ["确定", "取消"],
            //    yes: function (index, layero) {
            //        var iframeWin = window[layero.find('iframe')[0]['name']];
            //        var obj = frames['layui-layer-iframe' + index].getSelectData();
            //        if (obj.flag === false) {
            //            layer.alert(obj.msg, { icon: 2 });
            //        } else {
            //            for (var i = 0; i < obj.data.length; i++) {
            //                var name = name + "," + obj.data[i].CompanyName;
            //                var id = id + "," + obj.data[i].Id;
            //                var names = name.slice(10);
            //                var ids = id.slice(10);
            //                $("#CompanyNames").val(names)
            //                $("#CompanyIds").val(ids);
            //            }
            //            layer.close(index);
            //        }
            //    },
            //    btn2: function (index, layero) {
            //        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
            //        parent.layer.close(index);//关闭窗口
            //    },
            //    cancel: function (index, layero) {
            //    },
            //});
        });

        //变更资料上传
        var fileDataArrayFile = [];
        var fileDataJsonFile = [];
        //获取附件
        $.post("/Files/GetFileList", { tableName: 'Epm_Change', id: '@Model.Id' }, function (data) {
            if (data.Flag) {
                if (data.Data.length > 0) {
                    data.Data.forEach(function (item, index, arr) {
                        fileDataArrayFile.push({
                            GuidId: item.GuidId,
                            Name: item.Name,
                            Size: item.Size,
                            FileGuid: item.FileGuid,
                            Url: item.Url,
                            ImageType: item.ImageType
                        })
                        if (!isThumbnailImage(item.ImageType)) {
                            var odiv = '<li id="' + item.GuidId + '">';
                            odiv += '<div><img src="' + getFileImg(item.Name) + '" style="width: 20px;height: 20px;cursor: pointer;" class="imgShow"/><a href="' + FileDownLoadURL + item.FileGuid + '" target="_blank">' + item.Name + '</a></div>';
                            odiv += '<div>' + Number(item.Size / 1024).toFixed(2) + 'kb</div>';
                            odiv += '<div class="fileComplete"><img src="/Resource/images/default_ok.png" alt="完成" /></div>';
                            odiv += '<div><img src="/Resource/images/delete_default.png" class="fileDel" data-val="' + item.GuidId + '" style="cursor: pointer;"/></div>'
                            odiv += '</li>';
                            $('#fileListFile .fileShow').append(odiv);
                        }

                    })
                    fileDataJsonFile = JSON.stringify(fileDataArrayFile);
                    $("#fileDataJsonFile").val(fileDataJsonFile);
                }
            } else {
                parent.layer.alert(data.Message, { icon: 2 });
            }
        });
        //上传附件
        var uploaderFile = new plupload.Uploader({
            runtimes: 'html5,flash,silverlight,html4', // 这里是说用什么技术引擎
            url: FileServerURL, // 服务端上传路径
            max_file_size: MaxFileSize, // 文件上传最大限制。
            max_file_count: 10, //指示用户可以同时上传文件的最大数量
            chunk_size: 0, // 上传分块每块的大小，这个值小于服务器最大上传限制的值即可,0表示不启用分块。
            browse_button: 'btnUploadFile',//触发上传元素
            flash_swf_url: '/Resource/scripts/plupload_2_1_2/Moxie.swf',
            silverlight_xap_url: '/Resource/scripts/plupload_2_1_2/Moxie.xap',
            multi_selection: true,//	是否可以在文件浏览对话框中选择多个文件
            multipart_params: {//附加参数
                app: 'epm',
                crop: true
            },
            //  这个数组是选择器，就是上传文件时限制的上传文件类型，在chrome下有bug，要等待
            filters: {
                mime_types: [
                    { title: "Doc files", extensions: "doc,docx,xls,xlsx,rar,zip,7z,gif,rmvb,mp4,avi,jpg,png,jpeg" },
                ],
                max_file_size: MaxFileSize, //最大只能上传100mb的文件
                prevent_duplicates: true //不允许选取重复文件
            },
            rename: false, // 是否重命名文件
            init: {
                PostInit: function () { },
                FilesAdded: function (uploaderFile, files) {
                    if (files) {
                        files.forEach(function (item, index, arr) {
                            var imgUrl = getFileImg(item.name);
                            var odiv = '<li id="' + item.id + '">';
                            odiv += '<div><img src="' + imgUrl + '" style="width: 20px;height: 20px;cursor: pointer;" class="imgShow"/><a href="javascript:;" target="_blank">' + item.name + '</a></div>';
                            odiv += '<div>' + plupload.formatSize(item.size) + '</div>';
                            odiv += '<div class="fileComplete"><span class="fileProgress" style="cursor: pointer;">' + item.percent + '</span>%</div>';
                            odiv += '<div><img src="/Resource/images/delete_default.png" class="fileDel" data-val="' + item.id + '" style="cursor: pointer;"/></div>'
                            odiv += '</li>';
                            $('#fileListFile .fileShow').append(odiv);
                        })
                        uploaderFile.start();
                    }
                },
                UploadProgress: function (uploaderFile, file) {
                    $("#" + file.id).find(".fileProgress").html(file.percent)
                },
                FileUploaded: function (uploaderFile, file, responseObject) {
                    var data = JSON.parse(responseObject.response);
                    data.file.forEach(function (item, index, arr) {
                        var obj = {};
                        obj.GuidId = file.id;
                        obj.Name = item.Name;
                        obj.Size = item.FileSize;
                        obj.FileGuid = item.Guid;
                        obj.Url = item.VirtualURL;
                        if (IsImage(item.Extension)) {
                            obj.ImageType = getImageType(item.Name, item.Extension);
                        }
                        fileDataArrayFile.push(obj);
                    })
                    var img = '<img src="/Resource/images/default_ok.png" alt="完成" />'
                    $("#" + file.id).find(".fileComplete").html(img);
                    $("#" + file.id).find("a").prop("href", FileDownLoadURL + data.file[0].Guid)
                    uploaderFile.removeFile(file);

                },
                UploadComplete: function (uploaderFile, file, responseObject) {
                    fileDataJsonFile = JSON.stringify(fileDataArrayFile);
                    $("#fileDataJsonFile").val(fileDataJsonFile);
                },
                Error: function (up, err) {
                    layer.alert("错误：" + err.code + ": " + err.message);

                }
            },

        });
        uploaderFile.init();
        //删除附件
        $("#fileListFile").on("click", ".fileDel", function () {
            $(this).parents("li").remove();
            var toremove = '';
            var id = $(this).data("val");
            //----删除初始文件对应的值
            fileDataArrayFile = fileDataArrayFile.filter(function (item, index, arr) {
                return item.GuidId != id
            })
            fileDataJsonFile = JSON.stringify(fileDataArrayFile);
            $("#fileDataJsonFile").val(fileDataJsonFile);
        });
        //废弃
        $(".Discard").click(function () {
            var id = '@Model.Id';
            var state = "Discarded";
            if (id != "") {
                parent.layer.confirm("确认要废弃所选择的项？", { icon: 3 }, function () {
                    $.post("UpdateState", { id: id, state: state }, function (data) {
                        if (data.Flag) {
                            parent.layer.msg("废弃成功", { time: 2000, icon: 1 });
                            window.location.href = "/Change/Index";
                        } else {
                            parent.layer.alert(data.Message, { icon: 2 });
                        }
                    }, "json");
                }, function () {
                    return;
                })
            }
        });

        //驳回
        $(".Reject").click(function () {
            var id = '@Model.Id';
            var state = "ApprFailure";
            parent.layer.prompt({
                formType: 2,
                value: '',
                title: '请输入驳回理由'
            }, function (value, index, elem) {
                $.post("UpdateState", { id: id, reason: value, state: state }, function (data) {
                    if (data.Flag) {
                        parent.layer.msg("驳回成功", { time: 2000, icon: 1 });
                        window.location.href = "/Change/Index";
                    } else {
                        parent.layer.alert(data.Message, { icon: 2 });
                    }
                }, "json");
            }, function () {
                return;
            })
        });
        //审核
        $(".Audit").click(function () {
            var id = '@Model.Id';
            var state = "ApprSuccess";
            parent.layer.prompt({
                formType: 2,
                value: '',
                title: '请输入审核理由'
            }, function (value, index, elem) {
                $.post("UpdateState", { id: id, reason: value, state: state }, function (data) {
                    if (data.Flag) {
                        parent.layer.msg("审核成功", { time: 2000, icon: 1 });
                        window.location.href = "/Change/Index";
                    } else {
                        parent.layer.alert(data.Message, { icon: 2 });
                    }
                }, "json");
            }, function () {
                return;
            })
        });
        //沟通
        $(".exchange").click(function () {
            var projectName = $("#ProjectName").val();
            var projectId = $("#ProjectId").val();
            window.location.href = "/Question/Add?businType=Change&projectName=" + projectName + "&projectId=" + projectId;
        });
    </script>
</body>
